package com.xgr.wonderful;

import java.util.ArrayList;
import java.util.List;

import org.android.agoo.client.BaseRegistrar;

import android.R.integer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easemob.EMConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.EasyUtils;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.umeng.fb.FeedbackAgent;
import com.umeng.message.PushAgent;
import com.umeng.update.UmengUpdateAgent;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.AdActivity;
import com.xgr.wonderful.activity.CommentReceivedActivity;
import com.xgr.wonderful.activity.ConversationActivity;
import com.xgr.wonderful.activity.PublishStatusActivity;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.constant.HttpGetUrl;
import com.xgr.wonderful.db.DatabaseUtil;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.entity.SuperConversation;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.ActivityManagerUtils;
import com.xgr.wonderful.utils.Cache;
import com.xgr.wonderful.utils.HXUtils;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.NetworkUtil;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.utils.LocationUtils;
import com.xgr.wonderful.utils.Sputil;

/**
 * SlidingFragmentActivity extends FragmentActivity
 * 
 * @author lsj
 * 
 */
public class MainActivity extends SlidingFragmentActivity {
	private static String TAG = "MainActivity";

	private NaviFragment naviFragment;
	private ActionBar mActionBar; // by lsj
	private SlidingMenu mSlidingMenu;

	private NotificationManager mNotificationManager;
	private Notification notification ;
	private NewMsgBroadcastRecevier newMsgRecevier;

	private HttpProxy httpProxy ;
	private Sputil mSputil;
	private Intent currentIntent;

	private boolean mNeedAddStatusHome = false;//在发表新状态后用的
	private Status mStatusNeedAdd;
	
	String[] mTitles; 
	
	//通知活动相关
	private RelativeLayout mNotifyLayout ;
	private TextView mNotifyText ;
	private RelativeLayout mAdLayout ;
	
	private boolean appKill= false ; //退出机制控制

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 换成activity_center_v2
		setContentView(R.layout.activity_center_v2);
		mSputil = new Sputil(MainActivity.this, Constant.BASIC_PRE_NAME);
		mTitles = getResources().getStringArray(R.array.navigations) ;
		
		appKill = !NetworkUtil.isAvailable(this) ;
		
		init();
		onUmengInit();

		// 开始定位操作,init在application中
		LocationUtils.getInstance().doLocate();
		// 因为原来 MainActivity_v2没有加入，加入可以解决退出的问题
		MyApplication.getInstance().addActivity(this);

		newMsgRecevier = new NewMsgBroadcastRecevier();
		HXUtils.EMRegisterReceiver(MainActivity.this, newMsgRecevier,
				Constant.NEW_MESSAGE_PRIORITY_LOW);
		EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
		EMChat.getInstance().setAppInited();
	}

	/**
	 * should be done in onCreate in MainActivity,not in application
	 */
	private void onUmengInit() {
		// umeng更新的
		UmengUpdateAgent.update(this);
		// umeng推送，下面这句可以按是否活跃进行推送
		PushAgent.getInstance(this).onAppStart();
		if (mSputil.getValue("isPushOn", true)) {
			PushAgent pushAgent = PushAgent.getInstance(this);
			pushAgent.enable();
			// 要放丰enable后面，用于测试
			String device_token = BaseRegistrar.getRegistrationId(this);
			LogUtils.i(TAG, "umeng token:" + device_token);
		} else {
			PushAgent pushAgent = PushAgent.getInstance(this);
			pushAgent.disable();
		}
		// umeng反馈的，暂时没有用
		new FeedbackAgent(this).sync();
	}

	private void init() {
		mActionBar = (ActionBar) findViewById(R.id.actionbar_center);
		mAdLayout = (RelativeLayout)findViewById(R.id.center_ad_rl) ;
		mNotifyLayout = (RelativeLayout)findViewById(R.id.center_notify_comment_rl);
		mNotifyText = (TextView)findViewById(R.id.center_notify_comment_tv) ;
		mNotifyLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent1 = new Intent(getBaseContext() , CommentReceivedActivity.class) ;
				startActivity(intent1) ;
			}
		}) ;
		//进入 宣传页面，是一个webview 
		mAdLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent1 = new Intent(getBaseContext() , AdActivity.class) ;
				startActivity(intent1) ;
			}
		}) ;
		// 包含SlidingMenu对象
		mSlidingMenu = getSlidingMenu();
		setBehindContentView(R.layout.frame_navi);
		naviFragment = new NaviFragment();
		// 因为这是 是FragmentActivity中得到FragmentManager,所以是getSupport
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.frame_navi, naviFragment).commit();
		// 设置slidingmenu的属性
		mSlidingMenu.setMode(SlidingMenu.LEFT);// 设置slidingmen从哪侧出现
		mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);// 只有在边上才可以打开
		mSlidingMenu.setShadowDrawable(R.drawable.shadow);
		mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width) ;
		mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);// 设置划出时主页面显示的剩余宽度  
		//mSlidingMenu.setBehindWidth(400);//设置SlidingMenu菜单的宽度
		mSlidingMenu.setFadeEnabled(true);
		mSlidingMenu.setFadeDegree(0.3f);//SlidingMenu滑动时的渐变程度
		mSlidingMenu.setMenu(R.layout.frame_navi);
		// topbar设置
		mActionBar.setTitle("微圈");
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setHomeAction(new Action() {
			@Override
			public void performAction(View view) {
				mSlidingMenu.toggle();
			}

			@Override
			public int getDrawable() {
				return R.drawable.hambuger1; //old topleftmenu
			}
		});

	}

	/**
	 * 当fragment启动activity并且回传数据给fragment时
	 * 需要重写此方法，从而使fragment的onActivityResult被调用
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case Constant.REQUEST_CODE_PUBLISH_STATUS: // 发表新的状态后刷新数据
				mStatusNeedAdd = (Status) data
						.getSerializableExtra(Constant.STATUS_FROM_SERVER);
				setNeedAddStatusHome(true);// 说明需要在主页 第一个加入自己刚刚发表的状态
				break;
			default:
				super.onActivityResult(requestCode, resultCode, data);
				break;
			}
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			unregisterReceiver(newMsgRecevier);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	private static long firstTime;

	@Override
	public void onBackPressed() {
		// 两次返回键之间的时间间隔小于两秒，则退出
		if (firstTime + 2000 > System.currentTimeMillis()) {
			if (!appKill){//一开始就是有网络的，默认这种情况下软件正常工作
				//不再释放所有的activity，而是只保存一些 信息，然后回到主页 
				LogUtils.i(TAG, "not kill");
				MyApplication.getInstance().exit();
				Intent i = new Intent(Intent.ACTION_MAIN);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				i.addCategory(Intent.CATEGORY_HOME);
				startActivity(i);
				//ActivityManagerUtils.getInstance().removeAllActivity();
			}else { //一开始是没有网络的，应该直接全部关闭
				LogUtils.i(TAG, "kill");
				MyApplication.getInstance().exit();
				ActivityManagerUtils.getInstance().removeAllActivity();
			}
		} else {
			ToastFactory.getToast(this, "再按一次退出程序").show();
		}
		firstTime = System.currentTimeMillis();
	}
	
	/**
	 * 比较复杂 
	 * @param message
	 */
	private void notifyNewMessage(EMMessage message){
		if (!EasyUtils.isAppRunningForeground(this)){
			LogUtils.i(TAG, "app running forground") ;
			return ;
		}
		LogUtils.i(TAG, "notify");
		if (notification == null){
			notification = new Notification() ;
			notification.icon= R.drawable.weix_logo_blank ;
			notification.flags= Notification.FLAG_AUTO_CANCEL ;
		}
		if (mNotificationManager == null){
			mNotificationManager = (NotificationManager) getSystemService(
					Context.NOTIFICATION_SERVICE);
		}
		String from = message.getFrom() ;
		String msgid = message.getMsgId() ;
		if (message.getBooleanAttribute(Constant.COMMENT_PUSH_BY_HX, false)== true){
			//评论提醒 
			String pushStatusJson = ((TextMessageBody)message.getBody()).getMessage();
			LogUtils.i(TAG, "pushStatus:"+ pushStatusJson) ;
			String fromUsername = message.getStringAttribute(Constant.COMMENT_PUSH_FROM, "") ;
			LogUtils.i(TAG, "status:"+ pushStatusJson) ;
			//Cache.putCommentReceivedStatus(pushStatusJson) ;
			Status pushStatus  = null;
			try {
				pushStatus = new Gson().fromJson(pushStatusJson, Status.class) ;
				List< Status> commentReceivedStatus = Cache.getCommentRecevicedStatus() ;
				if (commentReceivedStatus!= null && commentReceivedStatus.size()!= 0){
					//已经 存在收到的评论,则要更新一下数据 
					for (Status temp : commentReceivedStatus){
						if (String.valueOf(temp.getId()).equals(String.valueOf(pushStatus.getId()))){
							commentReceivedStatus.remove(temp) ;//这里先删除 再添加 ，可以改变 顺序
						}
					}
				}else {
					commentReceivedStatus = new ArrayList<Status>() ;
				}
			    commentReceivedStatus.add(pushStatus) ;
			    //保存下来
				Cache.putCommentReceivedStatus(new Gson().toJson(commentReceivedStatus)) ;
			} catch (Exception e) {}
			//intent.putExtra("data", pushStatus);//
			Intent intent = new Intent(this ,CommentReceivedActivity.class) ;
			PendingIntent pendingIntent = PendingIntent.getActivity(this , 
					Constant.NEW_COMMENT_NOTIFICATION_ID, intent, Intent.FLAG_ACTIVITY_NEW_TASK) ;
			notification.tickerText= "收到来自"+fromUsername+"的评论";
			notification.setLatestEventInfo(this, "微圈", "收到来自"+fromUsername+"的评论",pendingIntent);
			mNotificationManager.notify(Constant.NEW_COMMENT_NOTIFICATION_ID,
					notification);
			//如果是评论，要删除这条消息,以免在聊天里面显示
			EMChatManager.getInstance().getConversation(from).removeMessage(msgid) ;
			handler.sendEmptyMessage(1) ;//刷新界面 
		}else {
			//收到的是新的消息，此时应该先查看是否是新的聊天，如果不是，则不用再管，如果是，应该再拉取聊天用户的信息
			if (DatabaseUtil.getInstance().getConversation(Integer.valueOf(from))== null){
				String url = HttpGetUrl.GetUser() + "?id="+ from.toString();
				httpProxy = new HttpProxy() ;
				httpProxy.queryUserByUserID(url, new IHttpRequestListener() {
					
					@Override
					public void OnHttpRequestSuccessful(String result, int errCode) {
						if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
							User remoteUser = null ;
							try {
								remoteUser = new Gson().fromJson(result, User.class);
							} catch (Exception e) {}
							if (remoteUser!= null && remoteUser.getUsername()!= null){
								//下面这句应该可以不加，不清楚
								LogUtils.i(TAG, "new conversation msg push and get user info ok") ;
								DatabaseUtil.getInstance().initConversationDao(getApplicationContext()) ;
								SuperConversation superConversation = new SuperConversation(
										remoteUser.getID(), remoteUser.getUsername(),
										remoteUser.getPhoto());
								DatabaseUtil.getInstance().addConversation(
										remoteUser.getID(), superConversation);
							}
						}
					}
					@Override
					public void OnHttpRequestStart() {
					
					}	
					@Override
					public void OnHttpRequestFailure(String info) {
					}
				}) ;
			}
			//原来就有的会话，直接通知就行了(上面的查询过程，是单独在一个线程进行的)
			Intent intent1 = new Intent(this, ConversationActivity.class );
			PendingIntent pendingIntent = PendingIntent.getActivity(this , 
					Constant.NEW_MESSAGE_NOTIFICATION_ID, intent1, Intent.FLAG_ACTIVITY_NEW_TASK) ;
			notification.tickerText= "收到了新的消息";
			notification.setLatestEventInfo(this, "微圈", "收到了新消息",pendingIntent);
			mNotificationManager.notify(Constant.NEW_MESSAGE_NOTIFICATION_ID,
					notification);
			//下面是收到消息时状态设置与界面刷新
			mSputil.setIsNewMsg(true) ;
			handler.sendEmptyMessage(2) ;
		}
	}
	private class NewMsgBroadcastRecevier extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			abortBroadcast();
			String username = intent.getStringExtra("from");
			String msgid = intent.getStringExtra("msgid");
			EMMessage message = EMChatManager.getInstance().getMessage(msgid);
			// 评论推送
			if (message.getBooleanAttribute(Constant.COMMENT_PUSH_BY_HX, false) == true) {
				notifyNewMessage(message) ;
				return;
			}else {
				//如果 是新的会话，如果 是已经 有的会话，实际是不用提示，但是要考虑保存用户信息的问题
				notifyNewMessage(message) ;
			}
		}
	}

	private class MyConnectionListener implements EMConnectionListener {
		@Override
		public void onConnected() {
		}

		@Override
		public void onDisconnected(int arg0) {

		}
	}

	// 在发表新的状态后返回为true
	public boolean getNeedAddStatusHome() {
		return mNeedAddStatusHome;
	}

	public void setNeedAddStatusHome(boolean needAdd) {
		mNeedAddStatusHome = needAdd;
	}

	public Status getStatusNeedAdd() {
		return mStatusNeedAdd;
	}
	//处理收到消息时的变化 
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (getIndex()==1){
				switch (msg.what) {
				case 1:
					refreshCommentNotify() ;
					break;
				case 2:
					//这里更新了action的图标 
					refreshNewMsg();
					break ;
				default:
					break;
				}
			}
		}
		
	} ;
	//默认时
	private int msgIconId = R.drawable.ic_action_message2 ;
	//收到消息后，更改消息的图标 
	private void refreshNewMsg(){
		if (mSputil.isNewMsg()){
			msgIconId = R.drawable.ic_action_message3 ;
		}else {
			msgIconId= R.drawable.ic_action_message2;
		}
		//刷新下action图标 
		if (getIndex()==1){
			onNaviItemSelected(getIndex()) ;
		}
	}

	/**
	 * 标题的设置，在NaviFragment中使用,同时还设置对应的actionbar 
	 * HOME =1
	 * @param title
	 */
	private int index =-1 ;
	public void setIndex (int index){
		this.index = index ;
	}
	public int getIndex (){
		return index ;
	}
	public void onNaviItemSelected(int index) {
		setIndex( index) ;
		mActionBar.setTitle(mTitles[index]);
		mActionBar.removeAllActions() ;
		mNotifyLayout.setVisibility(View.GONE) ;
		mAdLayout.setVisibility(View.GONE) ;
		switch (index) {
		case 0:	
			break;
		case 1:
			mActionBar.addAction(new ConversationAction()) ;
			mActionBar.addAction(new PublishStatusAction());
			refreshCommentNotify() ;
			refreshAddShow();
			break ;
		case 2:
			break ;
		case 3:
			break ;
		case 4:
			break ;
		default:
			break;
		}
		
	}
	
	/**
	 * 这个 是在干什么 ？ onCreate()->onStart()->onResume()方面里进行刷新操作。
	 * 因为按照activity的生命周期模型，当activity恢复的时候， onResume()方法会被调用，所以这是一个刷新的好机会。
	 */
	@Override
	protected void onResume() {
		super.onResume();
		LogUtils.i(TAG, "onResume") ;
		if (getIndex()==1){
			refreshCommentNotify() ;//主界面 时
			refreshAddShow() ;
			refreshNewMsg() ;
		}
	}
	private void refreshAddShow(){
		if (mSputil.isAdShow()){
			mAdLayout.setVisibility(View.VISIBLE) ;
		}else {
			mAdLayout.setVisibility(View.GONE);
		}
	}
	/**
	 * 查看 是否有收到评论，如果有，显示，否则 不显示,动作的监听在init中完成 
	 */
	private void refreshCommentNotify(){
		List<Status> commentReceivedStatus = Cache.getCommentRecevicedStatus() ;
		if (commentReceivedStatus == null|| commentReceivedStatus.size()==0){
			mNotifyLayout.setVisibility(View.GONE) ;
		}else {
			mNotifyLayout.setVisibility(View.VISIBLE) ;
			mNotifyText.setText(commentReceivedStatus.size()+"条状态收到评论") ;
		}
	}
	
	private class PublishStatusAction implements Action{
		@Override
		public void performAction(View view) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, PublishStatusActivity.class);
			// 为了在发表后刷新界面
			startActivityForResult(intent,
					Constant.REQUEST_CODE_PUBLISH_STATUS);
		}
		@Override
		public int getDrawable() {
			return R.drawable.ic_action_edit;
		}
		
	}
	
	private class ConversationAction implements Action{
		@Override
		public void performAction(View view) {
			Intent intent1 = new Intent(MainActivity.this, ConversationActivity.class); 
			startActivity(intent1) ;
		}
		
		@Override
		public int getDrawable() {
			// 可以根据是否有新的消息，来更换不同的图标 
			return msgIconId; 
		}
	}



}